package com.iretailer.report.quartz.systemTask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iretailer.report.model.Categories;
import com.iretailer.report.model.Malls;
import com.iretailer.report.service.CategoriesService;
import com.iretailer.report.service.CollectService;
import com.iretailer.report.service.MallsService;
import com.iretailer.report.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Auther Bennie
 * @Date 2020/6/15 10:37
 * @Description
 */
@Slf4j
@Service
public class CollectTask {
    private static final ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
    private final MallsService mallsService;
    private final CollectService collectService;
    private final CategoriesService categoriesService;

    public CollectTask(MallsService mallsService, CollectService collectService, CategoriesService categoriesService) {
        this.mallsService = mallsService;
        this.collectService = collectService;
        this.categoriesService = categoriesService;
    }

    public void execute() {
        long start = System.currentTimeMillis();
        List<Categories> zoneTypes = categoriesService.findChildrenCategoriesByKeyName("ZoneTypes");
        //查出所有Mall
        List<Malls> malls = mallsService.list(new QueryWrapper<Malls>().lambda().eq(Malls::getEnabled, 1));
        CountDownLatch latch = new CountDownLatch(malls.size());
        for (Malls m : malls) {
            pool.execute(() -> {
                long start_run = System.currentTimeMillis();
                ZonedDateTime time = ZonedDateTime.of(LocalDateTime.now().plusMinutes(-30), ZoneId.of(m.getTimeZone()));
                List<String> dates = new ArrayList<>();
                String date = TimeUtil.zoneDateTime_format(time, "yyyy-MM-dd");
                dates.add(date);
                collectService.runFlow(zoneTypes, m, dates);
                long end_run = System.currentTimeMillis();
                log.info("---- {} {} time:{}", m.getName(), date, (end_run - start_run));
                latch.countDown();
            });

        }
        try {
            latch.await(30, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        log.info("------ {} time:{}", LocalDateTime.now(), (end - start));
    }
}
